# Define user and password here or gather them securely
$user = "your_domain\\your_user"    # Replace or obtain dynamically if needed
$pass = "your_password"            # Replace or obtain dynamically if needed

# Path to the rename script
$renameScriptPath = Join-Path -Path $PSScriptRoot -ChildPath "rename.ps1"

# Retrieve the fwUser value from registry
$fwClientName = (Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\FileWave\WinClient" -Name "fwuser").fwuser

# If the computer already has the desired name, clean up and exit
if ($fwClientName -ieq $env:COMPUTERNAME) {
    if (Test-Path -Path $renameScriptPath) {
        Remove-Item -Path $renameScriptPath -Force
    }
    exit 1
}

# Generate the rename.ps1 script
@"
\$user = "$user"
\$pass = ConvertTo-SecureString "$pass" -AsPlainText -Force
\$DomainCred = New-Object System.Management.Automation.PSCredential(\$user, \$pass)
\$fwClientName = (Get-ItemProperty -Path HKLM:\SOFTWARE\WOW6432Node\FileWave\WinClient -Name fwuser).fwuser
Rename-Computer -NewName \$fwClientName -DomainCredential \$DomainCred -Force
"@ | Set-Content -Path $renameScriptPath -Encoding UTF8

# Run the rename script elevated
Start-Process -FilePath "powershell.exe" `
    -ArgumentList "-NoProfile", "-ExecutionPolicy Bypass", "-File `"$renameScriptPath`"" `
    -Verb RunAs

# Schedule a reboot with notification
Start-Sleep -Seconds 3
shutdown.exe /r /t 60 /c "Computer renamed to $fwClientName. Rebooting in 60 seconds." /f /d p:4:1

exit 2
